package com.itheima.stock.config;

import com.itheima.stock.pojo.vo.TaskThreadPoolInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import javax.annotation.PostConstruct;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 定义线程池相关配置
 * @author : itheima
 * @description :
 */
@Configuration
@EnableConfigurationProperties({TaskThreadPoolInfo.class})
public class TaskExecutePool {
    private TaskThreadPoolInfo info;

    public TaskExecutePool(@Autowired TaskThreadPoolInfo taskThreadPoolInfo) {
        this.info = taskThreadPoolInfo;
    }

    /**
     * 定义线程池bean
     * @return
     */
    @Bean(destroyMethod = "shutdown")
    public ThreadPoolTaskExecutor threadPoolTaskExecutor(){
        ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
        pool.setCorePoolSize(info.getCorePoolSize());//核心线程数
        pool.setMaxPoolSize(info.getMaxPoolSize());//最大线程数
        pool.setKeepAliveSeconds(info.getKeepAliveSeconds());//空闲线程超时淘汰时间
        pool.setQueueCapacity(info.getQueueCapacity());//队列长度
        pool.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());//设置拒绝策略
        pool.initialize();
        return pool;
    }

}
